/**
 * 微信支付 - 下单
 */
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
    console.log(event);
    // 校验参数
    const {
        goodsId,
        goodsName,
        price,
        count = 1,
        addressId,sellerId,buyerId,remarks
    } = event.data
    if (!goodsId || !goodsName || !price) {
        return {
            success: false,
            message: '商品信息不完整'
        }
    }
    const wxContext = cloud.getWXContext();

    // 商户自行生成商户订单号，此处仅为代码示例
    const outTradeNo = `loop${Date.now()}${Math.floor(Math.random() * 1000)}`
    
    const paymentResult = await cloud.callFunction({
        name: 'cloudbase_module',
        data: {
            name: 'wxpay_order',
            data: {
                description: goodsName,
                amount: {
                    total: Math.floor(price * 100), // 订单金额
                    currency: 'CNY',
                },
                // 商户生成的订单号
                out_trade_no: outTradeNo,
                payer: {
                    // 服务端云函数中直接获取当前用户openId
                    openid: wxContext.OPENID,
                },
            },
        },
    });
    // 保存订单到数据库
    const orderData = {
        goodsId,
        goodsName,
        price,
        count,
        addressId,
        outTradeNo,
        sellerId,
        buyerId,
        remarks,
        status: 1,
        createTime: db.serverDate(),
        paymentResult,
        isDeleted:false
    }

    const orderRes = await db.collection('orders').add({
        data: orderData
    })
    console.log(paymentResult);
    // 返回支付参数给前端
    return {
        success: true,
        orderId: orderRes._id,
        outTradeNo: outTradeNo,
        paymentParams: paymentResult.result.data
    }
};